package com.xiao.xin.core.service.Impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.xiao.xin.core.Mapper.UserResultMapper;
import com.xiao.xin.core.Util.UserThreadLocal;
import com.xiao.xin.core.domain.QueryTasklist;
import com.xiao.xin.core.domain.UserResult;
import com.xiao.xin.core.service.UserFundRecordService;
import com.xiao.xin.core.service.UserResultService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;

/**
* <p>
* user_result Service 接口实现
* </p>
*
* @author Administrator
* @since 2025-07-18 15:53:06
*/
@RequiredArgsConstructor
@Service
@Slf4j
public class UserResultServiceImpl extends ServiceImpl<UserResultMapper, UserResult> implements UserResultService {

    private final UserFundRecordService userFundRecordService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertUserResult(List<String> urls, long userId) {
        List<UserResult> list = urls.stream().map(new Function<String, UserResult>() {
            @Override
            public UserResult apply(String url) {
                return UserResult
                        .builder()
                        .userId(userId)
                        .url(url)
                        .collect(0)
                        .createTime(LocalDateTime.now())
                        .build();
            }
        }).toList();

        userFundRecordService.pointsDeduction(userId,list.size());

        saveBatch(list);
    }

    @Override
    public Map listUserResult(QueryTasklist queryTasklist) {
        Page<UserResult> page = Page.of(queryTasklist.getPageNum(), queryTasklist.getPageSize());
        Page<UserResult> resultPage = page(page, Wrappers.<UserResult>lambdaQuery().eq(UserResult::getUserId, UserThreadLocal.getUser().getId()));

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("code",200);
        hashMap.put("msg","ok");
        hashMap.put("data",resultPage.getRecords());
        hashMap.put("total",resultPage.getTotal());
        return hashMap;
    }
}